<template>
  <ContentWrap>
    <!--    顶部查询项-->
    <el-form :model="form" inline label-width="70px">
      <el-form-item :label="t('invoice.applicant')">
        <el-select
          v-model="form.applicant"
          :placeholder="'请选择' + t('invoice.applicant')"
          :filterable="true"
          :multiple="true"
          :clearable="false"
          style="width: 250px"
        >
          <el-option
            v-for="item in applicantList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('invoice.customer_id')">
        <el-select
          v-model="form.customer_id"
          :placeholder="'请输入' + t('order.customer') + '名称或邮箱'"
          :filterable="true"
          :multiple="true"
          :clearable="false"
          :remote="true"
          :remote-method="getCustomerOptions"
          :loading="selectLoading"
          style="width: 250px"
        >
          <el-option
            v-for="item in userList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item :label="t('invoice.order_type')">
        <el-select
          v-model="form.order_type"
          :placeholder="'请选择' + t('invoice.order_type')"
          :clearable="false"
          style="width: 250px"
        >
          <el-option
            v-for="item in orderTypeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item :label="t('invoice.order_id')">
        <el-input
          v-model="form.order_no"
          clearable
          :placeholder="'请输入' + t('invoice.order_id')"
          style="width: 250px"
        />
      </el-form-item>
      <el-form-item :label="t('invoice.invoice_no')">
        <el-input
          v-model="form.invoice_no"
          clearable
          :placeholder="'请输入' + t('invoice.invoice_no')"
          style="width: 250px"
        />
      </el-form-item>

      <el-form-item :label="t('invoice.status')">
        <el-select
          v-model="form.status"
          :placeholder="'请选择' + t('invoice.status')"
          :clearable="false"
          style="width: 250px"
        >
          <el-option
            v-for="item in statusList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item :label="t('invoice.invoicing_date')">
        <el-date-picker
          v-model="form.invoicing_date"
          type="daterange"
          range-separator="-"
          start-placeholder="起始时间"
          end-placeholder="结束时间"
          @change="changeTime"
          :editable="false"
          unlink-panels
          clearable
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="initialize">查询</el-button>
        <el-button icon="Refresh" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
    <!--    操作项-->
    <div class="flex flex-items-center my-5">
      <el-button type="primary" @click="handleAdd('add')">
        {{ t('action.add') }}
      </el-button>
    </div>
    <!-- 表格主体 -->
    <Table
      showAction
      :data="dataList"
      :columns="tableColumns"
      highlight-current-row
      stripe
      border
      :loading="tableLoading"
      align="center"
      header-align="center"
      row-key="id"
    />
    <!--    分页-->
    <Pagination
      :total="paginationTotal"
      v-model:page="form.pageIndex"
      v-model:limit="form.pageSize"
      @pagination="initialize"
    />
  </ContentWrap>
  <!--      上传支付审核弹框-->
  <DialogUpload ref="DialogUploadRef" @refresh="initialize" />
</template>

<script setup lang="ts">
import dayjs from 'dayjs'
import Pagination from '@/components/Pagination/index.vue'
import { ContentWrap } from '@/components/ContentWrap'
import { useEnumeratePicker } from '@/utils'
import { getEnumApi, getListApi } from '@/api/invoice'
import { getSelectApi as getCustomerSelectApi } from '@/api/customer'
import { getSelectListApi as getOperatorSelectListApi } from '@/api/operator'
import DialogUpload from '@/views/Order/Order/components/DialogUpload/index.vue'
import { Table } from '@/components/Table'
import { useInvoiceTableColumns } from './components/hooks/useTableColumns'

const { t } = useI18n()
const { push } = useRouter()

const tableLoading = ref<boolean>(false)
const dataList = ref<any[]>([])
const paginationTotal = ref<number>(0)
const DialogUploadRef = ref<InstanceType<typeof DialogUpload>>()
const selectLoading = ref<boolean>(false)

const form = ref<Record<string, any>>({
  order_no: '',
  applicant: '',
  customer_id: '',
  order_type: '',
  invoice_no: '',
  status: '',
  invoicing_date: [],
  start_time: '',
  end_time: '',
  pageIndex: 1,
  pageSize: 15
})

const orderTypeList = ref<Array<Record<string, any>>>([])
const invoiceTypeList = ref<Array<Record<string, any>>>([])
const statusList = ref<Array<Record<string, any>>>([])
const userList = ref<Array<Record<string, any>>>([])
const applicantList = ref<Array<Record<string, any>>>([])

// 客户异步下拉框
const getCustomerOptions = async (value) => {
  if (value) {
    selectLoading.value = true
    const userResp = await getCustomerSelectApi({ cusname: value })
    userList.value = userResp.data
    selectLoading.value = false
  }
}

//格式化时间
const changeTime = (e: Date[]) => {
  if (e && e.length > 0) {
    form.value.start_time = dayjs(e[0]).format('YYYY-MM-DD 00:00:00')
    form.value.end_time = dayjs(e[1]).format('YYYY-MM-DD 23:59:59')
  } else {
    form.value.start_time = null
    form.value.end_time = null
  }
}

//点击跳转到新增
const handleAdd = (type: string) => {
  console.log(`/order/invoice-management/${type}?source=/order/invoice-management`)
  push(`/order/invoice-management/${type}?source=/order/invoice-management`)
}

//获取枚举
const getDropDownBoxInfo = async () => {
  const resp = await getEnumApi({ field: 'all' })
  orderTypeList.value = resp.data.order_type
  invoiceTypeList.value = resp.data.invoice_type
  statusList.value = resp.data.status

  const applicantResp = await getOperatorSelectListApi({})
  applicantList.value = applicantResp.data.list
}

//初始化请求
const initialize = async () => {
  tableLoading.value = true
  const params = JSON.parse(JSON.stringify(form.value))
  delete params.date
  if (params.order_no && !params.order_type) {
    ElMessage.error('请选择' + t('invoice.order_type'))
    tableLoading.value = false
    return
  }
  const resp = await getListApi(params)
  dataList.value = resp.data.list

  paginationTotal.value = resp.data.total
  tableLoading.value = false
}

//重置查询项
const reset = () => {
  form.value = {
    order_no: '',
    applicant: '',
    customer_id: '',
    order_type: '',
    invoice_no: '',
    status: '',
    invoicing_date: [],
    start_time: '',
    end_time: '',
    pageIndex: 1,
    pageSize: 15
  }
  paginationTotal.value = 0
  initialize()
}

onActivated(() => {
  getDropDownBoxInfo()
  initialize()
})

const handleLink = (type: string, row: any) => {
  if (type === 'detail') {
    push({ path: '/order/invoice-management/detail', query: { id: row?.id } })
  }
}

const tableColumns = useInvoiceTableColumns(
  handleLink,
  useEnumeratePicker,
  applicantList,
  statusList,
  invoiceTypeList,
  dataList
)
</script>

<style lang="less" scoped></style>
